package com.rjh.concurrent.monitor;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.SyncWaitTest")
public class SyncWaitTest {

	public static void main(String[] args) {

		Guarded guarded = new Guarded();


		Thread t1 = new Thread(() -> {
			log.debug("into getResponse");
			synchronized (guarded){
				Object response = guarded.getResponse();
				log.debug("getResponse {}",response);
			}

		}, "t1");

		Thread t2 = new Thread(() -> {
			log.debug("into setResponse");
			synchronized (guarded){
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				guarded.setResponse("hello word!!");
				log.debug("setResponse over");
			}
		}, "t2");


		t1.start();
		t2.start();
	}
}


class Guarded {

	private Object response;


	public Object getResponse(long time) {
		//获取开始时间
		long currentTime = System.currentTimeMillis();
		//用于保存已经等待了的时间
		long passedTime = 0;
		while (response==null){
			synchronized (this){
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		return response;
	}


	public Object getResponse() {
		while (response==null){
			synchronized (this){
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		return response;
	}

	public void setResponse(Object response) {
		this.response = response;
		synchronized (this){
			this.notifyAll();
		}
	}

	@Override
	public String toString() {
		return "Guarded{" + "response=" + response + '}';
	}
}
